package com.controller;

import com.Security.encodeUtil;
import com.service.userService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

public class registerServlet extends HttpServlet {

    private userService userService=new userService();

    /**
     * register
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");

        String id = req.getParameter("userid");
        int userid = Integer.parseInt(id);
        String username = req.getParameter("username");
        String psd = req.getParameter("password");
        String password = encodeUtil.encode(psd); //encode后的密文
        String address = req.getParameter("address");


        try {
            if(userService.checkUserExist(userid)){
                req.getRequestDispatcher("registerFalse.jsp").forward(req,resp);
                return;
            }else {

                try {
                    boolean isRegister = userService.registerUser(userid, username, password, address);
                    if(isRegister){
                        req.getRequestDispatcher("registerSuccess.jsp").forward(req,resp);
                        return;
                    }else{
                        resp.sendRedirect("registerFalse.jsp");
                        return;
                    }


                } catch (SQLException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }

            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
